<template>
    <div class="storeManageHandle">
        <el-breadcrumb separator="/" class="bread-title">
            <el-breadcrumb-item>账户管理</el-breadcrumb-item>
            <el-breadcrumb-item :to="{ path: '/storeManage' }">经纪门店管理</el-breadcrumb-item>
            <el-breadcrumb-item>{{type2Text[type]}}</el-breadcrumb-item>
        </el-breadcrumb>
        <!--<div class="mb15">
            <el-button size="small" type="primary" @click="showAddCompany">添加公司</el-button>
        </div>-->
        <el-form ref="form" v-if="type==='view'" label-width="120px" size="small" :model="form">
            <el-form-item label="店铺所在城市：">{{viewForm.storesCity}}</el-form-item>
            <el-form-item label="公司名称：">{{viewForm.brokerCompanyName}}</el-form-item>
            <el-form-item label="门店名称：">{{form.storesName}}</el-form-item>
            <el-form-item label="服务板块：">{{viewForm.sysCityAreasName}}</el-form-item>
            <el-form-item label="门店归属：">{{viewForm.leaderName}} {{viewForm.leaderPhone}}</el-form-item>
            <el-form-item label="备注地址：">{{form.storeAddress}}</el-form-item>
            <el-form-item label="门店地址：">{{form.storeDrawAddress}}</el-form-item>
            <el-form-item label="经纬坐标：">{{form.storeDrawStuff}} {{form.storeDrawWoof}}</el-form-item>
        </el-form>


        <el-form ref="form" v-else label-width="120px" size="small" :model="form" :rules="rules">
            <el-form-item label="店铺所在城市：" prop="cityId">
                <el-select :disabled="type === 'edit'" filterable v-model="form.cityId" @change="onCityChange" placeholder="请选择店铺所在城市">
                    <el-option
                            v-for="item in allCityList"
                            :key="item.cityId"
                            :label="item.city"
                            :value="item.cityId">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="公司名称：" prop="brokerCompanyId">
                <el-select :disabled="!form.cityId || type === 'edit'" filterable v-model="form.brokerCompanyId" placeholder="请选择公司">
                    <el-option
                            v-for="item in allCompanyList"
                            :key="item.id"
                            :label="item.companyName"
                            :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="门店名称：" prop="storesName">
                <el-input style="width: 215px" v-model="form.storesName" placeholder="请输入门店名称"></el-input>
            </el-form-item>
            <el-form-item label="服务板块：" prop="sysCityAreasId">
                <el-select :disabled="!form.cityId" filterable v-model="form.sysCityAreasId" @change="onAreaChange" placeholder="请选择服务板块">
                    <el-option
                            v-for="item in allAreaList"
                            :key="item.areaid"
                            :label="item.area"
                            :value="item.areaid">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="门店归属：" prop="leaderId">
                <el-select v-model="form.leaderId" :disabled="!isAssignAble || !form.sysCityAreasId" filterable placeholder="请选择门店归属">
                    <el-option
                            v-for="item in allOwnershipList"
                            :key="item.leaderId"
                            :label="item.leaderName + ' ' + item.leaderPhone"
                            :value="item.leaderId">
                    </el-option>
                </el-select>
                <span style="color: red; margin-left: 10px;">备注：经服人员只能选择同一片区内的经服。</span>
            </el-form-item>

            <el-form-item label="备注地址：" prop="storeAddress">
                <el-input style="width: 240px" v-model="form.storeAddress" placeholder="详细地址"></el-input>
            </el-form-item>
            <el-form-item label="门店地址：" prop="storeDrawAddress">
                <el-input class="mr15" disabled style="width: 410px" v-model="form.storeDrawAddress"></el-input>
                <el-button size="small" type="primary" @click="showMapDialog">地图标注</el-button>
            </el-form-item>

            <el-form-item label="经纬坐标：" prop="storeDrawAddress">
                <el-input class="w100 tac mr15" disabled v-model="form.storeDrawStuff"></el-input>
                <el-input class="w100 tac" disabled v-model="form.storeDrawWoof"></el-input>
            </el-form-item>

            <el-form-item>
                <div class="mt50">
                    <el-button @click="goList">取消</el-button>
                    <el-button type="primary" @click="addStore">保存</el-button>
                </div>
            </el-form-item>
        </el-form>


        <!-- 添加公司 好像被删掉了 -->
        <!--<el-dialog
                title="新建公司"
                :visible.sync="dialogVisible"
                width="350px">
            <div>
                <el-form :inline="true" size="small" :model="dialogForm" class="demo-form-inline">
                    <el-form-item label="公司名称：">
                        <el-input style="width: 215px" v-model="dialogForm.user"></el-input>
                    </el-form-item>
                    <el-form-item label="公司地址：">
                        <el-input style="width: 215px" v-model="dialogForm.user"></el-input>
                    </el-form-item>
                    <el-form-item label="公司电话：">
                        <el-input style="width: 215px" v-model="dialogForm.user"></el-input>
                    </el-form-item>
                    <el-form-item label="公司城市：">
                        <el-select v-model="dialogForm.region" placeholder="请选择公司城市">
                            <el-option
                                    v-for="item in allCityList"
                                    :key="item.cityId"
                                    :label="item.city"
                                    :value="item.cityId">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
            </div>
            <div slot="footer" class="dialog-footer tac">
                <el-button size="small" class="mr10" @click="dialogVisible = false">取 消</el-button>
                <el-button size="small" type="primary" @click="dialogVisible = false">确 定</el-button>
            </div>
        </el-dialog>-->

        <el-dialog
                title="地图标注"
                :visible.sync="mapDialogVisible"
                custom-class="mapDialog"
                :fullscreen="true">
            <div class="map-Container">
                <div class="city-container">
                    <div class="city-container-current" style="cursor: pointer" @click="aMap.citySelectVisible = !aMap.citySelectVisible">
                        {{aMap.currentCity}}<i :class="{
                            'el-icon-arrow-down': !aMap.citySelectVisible,
                            'el-icon-arrow-up': aMap.citySelectVisible,
                            'ml10': true,
                        }"></i>
                    </div>
                    <el-card class="box-card" v-show="aMap.citySelectVisible">
                        <div slot="header" class="clearfix">
                            <span>当前城市：{{aMap.currentCity}}</span>
                            <i class="el-icon-close" @click="aMap.citySelectVisible = false" style="float: right; cursor: pointer"></i>
                        </div>
                        <div>
                            <div>
                                <el-button type="text" @click="citySelectChange('北京市')">北京市</el-button>
                                <el-button type="text" @click="citySelectChange('上海市')">上海市</el-button>
                                <el-button type="text" @click="citySelectChange('广州市')">广州市</el-button>
                                <el-button type="text" @click="citySelectChange('深圳市')">深圳市</el-button>
                                <el-button type="text" @click="citySelectChange('天津市')">天津市</el-button>
                                <el-button type="text" @click="citySelectChange('重庆市')">重庆市</el-button>
                                <el-button type="text" @click="citySelectChange('成都市')">成都市</el-button>
                                <el-button type="text" @click="citySelectChange('南京市')">南京市</el-button>
                                <el-button type="text" @click="citySelectChange('杭州市')">杭州市</el-button>
                            </div>
                            <div class="mt20">
                                <el-select v-model="aMap.selectCity" @change="citySelectChange" filterable placeholder="请选择城市">
                                    <el-option
                                            v-for="item in allCityList"
                                            :key="item.cityId"
                                            :label="item.city"
                                            :value="item.city">
                                    </el-option>
                                </el-select>
                            </div>
                        </div>
                    </el-card>
                </div>
                <el-amap-search-box class="search-box" :search-option="aMap.searchOption" :on-search-result="onSearchResult"></el-amap-search-box>
                <el-amap vid="amapDemo" :plugin="aMap.plugin" :center="aMap.mapCenter" :zoom="aMap.zoom" :events="aMap.events" class="amap-demo">
                    <el-amap-marker v-for="(marker,index) in aMap.markers" :key="index" :position="marker" :events="aMap.markerEvents"></el-amap-marker>
                    <!--<el-amap-marker v-if="aMap.manualAddMarker.length" :position="aMap.manualAddMarker"></el-amap-marker>-->
                    <el-amap-info-window
                            :position="aMap.infoWindow.position"
                            :content="aMap.infoWindow.content"
                            :visible="aMap.infoWindow.visible">
                    </el-amap-info-window>
                </el-amap>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button size="small" class="mr10" @click="mapDialogVisible = false">取 消</el-button>
                <el-button size="small" type="primary" @click="mapDialogSubmit">确 定</el-button>
            </div>
        </el-dialog>
        <el-tabs v-if="type === 'view'" v-model="recordName" @tab-click="">
            <el-tab-pane label="操作记录" name="操作记录">
                <el-table
                        :data="recordOperate"
                        tooltip-effect="dark"
                        border>
                    <el-table-column
                            type="index"
                            label="序号"
                            align="center"
                            width="55">
                    </el-table-column>
                    <el-table-column
                            prop="operateContent"
                            align="center"
                            label="操作">
                    </el-table-column>
                    <el-table-column
                            prop="createName"
                            align="center"
                            label="姓名">
                    </el-table-column>
                    <el-table-column
                            prop="createRole"
                            align="center"
                            label="角色">
                    </el-table-column>
                    <el-table-column
                            prop="createTime"
                            align="center"
                            label="时间">
                    </el-table-column>
                </el-table>
            </el-tab-pane>
            <el-tab-pane label="分配记录" name="分配记录">
                <el-table
                        :data="recordAssign"
                        tooltip-effect="dark"
                        border>
                    <el-table-column
                            type="index"
                            label="序号"
                            align="center"
                            width="55">
                    </el-table-column>
                    <el-table-column
                            prop="createName"
                            align="center"
                            label="操作人">
                    </el-table-column>
                    <el-table-column
                            prop="createTime"
                            align="center"
                            label="操作时间">
                    </el-table-column>
                    <el-table-column
                            prop="allocatOn"
                            align="center"
                            label="归属时间">
                    </el-table-column>
                    <el-table-column
                            prop="allocatEnd"
                            align="center"
                            label="截止时间">
                        <template slot-scope="scope">{{scope.row.allocatEnd || '——'}}</template>
                    </el-table-column>
                    <el-table-column
                            prop="allocatLeaderName"
                            align="center"
                            label="门店归属">
                    </el-table-column>
                </el-table>
            </el-tab-pane>
        </el-tabs>
    </div>
</template>

<script type="text/ecmascript-6">
    import Vue from 'vue'
    import VueAMap from 'vue-amap'  // 高德地图
    import {lazyAMapApiLoaderInstance} from 'vue-amap';

    Vue.use(VueAMap);
    VueAMap.initAMapApiLoader({
        key: '917924d751657009c7f54abe71069fdc',
        plugin: ['AMap.Scale', 'AMap.ToolBar', 'AMap.Autocomplete', 'AMap.PlaceSearch', 'Geocoder'],
        v: '1.4.4'
    });
    export default {
        name: 'storeManageHandle',
        data() {
            let _this = this;
            return {
                id: '',
                type: '',
                storeNumber: '',
                registrantCity: '',
                isAssignAble: false,
                type2Text: {
                    'new': '新建',
                    'edit': '编辑',
                    'view': '查看',
                },
                recordName: '操作记录',
                recordOperate: [],
                recordAssign: [],
                aMap: {
                    currentCity: '北京市',
                    selectCity: '',
                    citySelectVisible: false,
                    map: null,
                    zoom: 13,
                    mapCenter: [116.46772, 39.89148],
                    searchOption: {
                        city: '',
                        citylimit: false
                    },
                    markers: [],
                    // manualAddMarker: [],
                    infoWindow: {
                        position: [116.46772, 39.89148],
                        content: 'Hi! I am here too!',
                        visible: false
                    },
                    plugin: [
                        {
                            pName: 'Scale',
                        },
                        {
                            pName: 'ToolBar',
                        },
                        // {
                        //     pName: 'Geolocation',
                        //     events: {
                        //         init(o) {
                        //             o.getCurrentPosition((status, result) => {
                        //                 if (result && result.position) {
                        //                     _this.aMap.mapCenter = [result.position.lng, result.position.lat];
                        //                     _this.aMap.currentCity = result.addressComponent.city || result.addressComponent.province
                        //                 }
                        //             });
                        //         }
                        //     }
                        // }
                    ],
                    events: {
                        click(e) {
                            _this.clickMap(e)
                        }
                    },
                    markerEvents: {
                        click(e) {
                            _this.clickMap(e)
                        }
                    },
                    resultData: {
                        formattedAddress: '',
                        city: '',
                        lng: '',
                        lat: ''
                    }
                },
                allCityList: [],
                allAreaList: [],
                allCompanyList: [],
                allOwnershipList: [],
                form: {
                    cityId: '',
                    brokerCompanyId: '',
                    storesName: '',
                    sysCityAreasId: '',

                    leaderId: '',
                    storeAddress: '',
                    storeDrawAddress: '',
                    storeDrawStuff: '',
                    storeDrawWoof: '',
                },
                viewForm: {},
                rules: {
                    cityId: [
                        {required: true, message: '请选择店铺所在城市', trigger: 'blur'},
                    ],
                    brokerCompanyId: [
                        {required: true, message: '请选择公司名称', trigger: 'blur'},
                    ],
                    storesName: [
                        {required: true, message: '请输入门店名称', trigger: 'blur'},
                    ],
                    sysCityAreasId: [
                        {required: true, message: '请选择服务板块', trigger: 'blur'},
                    ],
                    // leaderId: [
                    //     {required: true, message: '请选择门店归属', trigger: 'blur'},
                    // ],
                    // storeAddress: [
                    //     {required: true, message: '请输入备注地址', trigger: 'blur'},
                    // ],
                    storeDrawAddress: [
                        {required: true, message: '请标注详细位置', trigger: 'blur'},
                    ]
                },

                mapDialogVisible: false,
                // dialogVisible: false,
                // dialogForm: {}
            }
        },
        mounted() {
            this.type = this.$route.query.type;
            this.id = this.$route.query.id;
            this.storeNumber = this.$route.query.storeNumber;

            if (this.id) {
                this.getDetail(this.id, this.storeNumber)
            }
            this.getAllCity()
            this.getPermissionStatus()
        },
        methods: {
            onCityChange() {
                this.form.sysCityAreasId = '';
                this.form.brokerCompanyId = '';
                this.form.leaderId = '';
                this.getOthersSelectData()
            },
            onAreaChange() {
                this.form.leaderId = '';
                this.getLeaderList()
            },
            getLeaderList() {
                // 门店归属人
                this.$axios.post("/cms/stores/stores/selectRegionLeader", {
                    serveId: this.form.sysCityAreasId
                }).then((res) => {
                    this.allOwnershipList = res
                })
            },
            getOthersSelectData() {
                //根据城市ID获取区（服务板块）
                this.$axios.post("/cms/stores/stores/selectAreaByCity", {
                    cityid: this.form.cityId
                }).then((res) => {
                    this.allAreaList = res
                })
                //根据城市ID获取经纪公司
                this.$axios.post("/cms/stores/stores/selectCompany", {
                    cityid: this.form.cityId
                }).then((res) => {
                    this.allCompanyList = res
                })
            },
            onSearchResult(pois) {
                this.aMap.markers = [];
                let latSum = 0;
                let lngSum = 0;
                if (pois.length > 0) {
                    pois.forEach(poi => {
                        let {lng, lat} = poi;
                        lngSum += lng;
                        latSum += lat;
                        this.aMap.markers.push([poi.lng, poi.lat]);
                    });
                    // 计算地图中心
                    let center = {
                        lng: lngSum / pois.length,
                        lat: latSum / pois.length
                    };
                    this.aMap.mapCenter = [center.lng, center.lat];
                }
            },
            /* 地图事件等 */
            clickMap(e) {
                // 获取点击的坐标和位置详细信息， 并地图打点Marker展示信息窗体
                let _this = this;
                let {lng, lat} = e.lnglat;
                // this.aMap.manualAddMarker = [lng, lat]
                this.aMap.infoWindow.visible = false
                let geocoder = new AMap.Geocoder({
                    radius: 1000,
                    extensions: "all"
                });
                geocoder.getAddress([lng, lat], (status, result) => {
                    if (status === 'complete' && result.info === 'OK') {
                        _this.aMap.resultData.lat = lat;
                        _this.aMap.resultData.lng = lng;
                        _this.aMap.resultData.city = result.regeocode.addressComponent.city || result.regeocode.addressComponent.province;
                        _this.aMap.resultData.formattedAddress = result.regeocode.formattedAddress;

                        _this.aMap.infoWindow.position = [lng, lat]
                        _this.aMap.infoWindow.content = `您现在选择的位置：[ <b>${lng} , ${lat}</b>] <br/> <b style="color: #333">${result.regeocode.formattedAddress}</b>`
                        setTimeout(() => {
                            _this.aMap.infoWindow.visible = true
                        }, 30)
                    }
                });

            },
            showAddCompany() {
                this.dialogVisible = true
            },
            showMapDialog() {
                this.mapDialogVisible = true;
                if (!this.aMap.map) {
                    lazyAMapApiLoaderInstance.load().then(() => {
                        this.aMap.map = new AMap.Map('amapContainer', {
                            center: new AMap.LngLat(121.59996, 31.197646),
                            resizeEnable: true,
                            zoom: 13
                        });
                        if (this.registrantCity && !this.form.storeDrawWoof) {
                            this.citySelectChange(this.registrantCity)
                        }
                    });
                }


                if (this.form.storeDrawStuff && this.form.storeDrawWoof) {
                    this.aMap.mapCenter = [this.form.storeDrawStuff, this.form.storeDrawWoof];
                    this.aMap.infoWindow.position = [this.form.storeDrawStuff, this.form.storeDrawWoof]
                    this.aMap.infoWindow.content = `您现在选择的位置：[ <b>${this.form.storeDrawStuff} , ${this.form.storeDrawWoof}</b>] <br/> <b style="color: #333">${this.form.storeDrawAddress}</b>`
                }
            },
            mapDialogSubmit() {
                if (this.aMap.resultData.formattedAddress) {
                    //console.log(this.aMap.resultData);
                    this.mapDialogVisible = false;
                    this.form.storeDrawStuff = this.aMap.resultData.lng
                    this.form.storeDrawWoof = this.aMap.resultData.lat
                    this.form.storeDrawAddress = this.aMap.resultData.formattedAddress
                } else {
                    this.$message.warning('请在地图上标注地点');
                }
            },

            getAllCity() {
                this.$axios.post('/city/cityList', {}).then((res) => {
                    this.allCityList = res.cityList
                    const cmsUser = JSON.parse(sessionStorage.getItem("cmsUser"));
                    if (cmsUser && this.type === 'new') {
                        this.form.cityId = cmsUser.cityId + '';
                        const registrantCity = this.allCityList.find((item) => {
                            return item.cityId == cmsUser.cityId
                        }) || {}
                        this.registrantCity = registrantCity.city;
                        this.getOthersSelectData()
                    }
                })
            },
            citySelectChange(cityName) {
                let placeSearch = new AMap.PlaceSearch();
                placeSearch.search(cityName, (status, result) => {
                    let {lng, lat} = result.poiList.pois[0].location;
                    this.aMap.mapCenter = [lng, lat];
                    this.aMap.selectCity = '';
                    this.aMap.currentCity = cityName;
                    this.aMap.citySelectVisible = false;
                });
            },

            addStore() {
                this.$refs.form.validate((valid) => {
                    if (valid) {
                        const city = this.allCityList.find((item) => {
                            return item.cityId === this.form.cityId
                        });
                        const company = this.allCompanyList.find((item) => {
                            return item.id === this.form.brokerCompanyId
                        });
                        const leader = this.allOwnershipList.find((item) => {
                            return item.leaderId === this.form.leaderId
                        }) || {};
                        // 老接口非要传这些东西，我也没办法
                        const backstageNeedParams = {
                            cityId: city.cityId,
                            storesCity: city.city,
                            companyName: company.companyName,
                            companyAddress: company.companyAddress,
                            contactPhone: company.contactPhone,
                            leaderName: leader.leaderName || '',  // 非必填字段
                            leaderPhone: leader.leaderPhone || '' // 非必填字段
                        };
                        // 编辑时，增加这两个字段
                        const editParams = {
                            id: this.id,
                            storeNumber: this.storeNumber
                        };
                        if (this.form.storeDrawAddress.indexOf(backstageNeedParams.storesCity) < 0) {
                            console.log(backstageNeedParams.storesCity, this.form.storeDrawAddress);
                            this.$message.warning("店铺所在城市和标注地址所在城市不一致！")
                            return false
                        }
                        this.$axios.post(`/cms/stores/stores/${this.id ? 'updateStores' : 'insertStore'}`, {
                            ...this.form,
                            ...backstageNeedParams,
                            ...editParams
                        }).then((res) => {
                            this.$message.success(this.type2Text[this.type] + '成功');
                            this.goList()
                        })
                    } else {
                        return false;
                    }
                });
            },
            goList() {
                this.$router.push({path: '/storeManage'})
            },
            getDetail(id, storeNumber) {
                this.$axios.post("/cms/stores/stores/fullStore", {
                    storeId: id,
                    storeCode: storeNumber
                }).then((res) => {

                    this.form = {
                        cityId: res.store.cityId,
                        brokerCompanyId: res.store.brokerCompanyId,
                        storesName: res.store.storesName,
                        sysCityAreasId: res.store.sysCityAreasId,
                        leaderId: res.store.leaderId || '',
                        storeAddress: res.store.storeAddress,
                        storeDrawAddress: res.store.storeDrawAddress,
                        storeDrawStuff: res.store.storeDrawStuff,
                        storeDrawWoof: res.store.storeDrawWoof,
                    }
                    this.viewForm = {
                        storesCity: res.store.storesCity,
                        brokerCompanyName: res.store.brokerCompanyName,
                        sysCityAreasName: res.store.sysCityAreasName,
                        leaderName: res.store.leaderName,
                        leaderPhone: res.store.leaderPhone,
                    }
                    if(this.form.storeDrawStuff && this.form.storeDrawWoof){
                        // 回显地图位置
                        this.aMap.resultData.lng = this.form.storeDrawStuff
                        this.aMap.resultData.lat = this.form.storeDrawWoof
                        this.aMap.resultData.formattedAddress = this.form.storeDrawAddress

                        this.aMap.infoWindow.position = [this.form.storeDrawStuff, this.form.storeDrawWoof]
                        this.aMap.infoWindow.content = `您现在选择的位置：[ <b>${this.form.storeDrawStuff} , ${this.form.storeDrawWoof}</b>] <br/> <b style="color: #333">${this.form.storeDrawAddress}</b>`
                        setTimeout(() => {
                            this.aMap.mapCenter = [this.form.storeDrawStuff, this.form.storeDrawWoof];
                            this.aMap.infoWindow.visible = true
                        }, 30)
                    }
                    this.getLeaderList()
                    this.getOthersSelectData()
                    this.recordOperate = res.operation
                    this.recordAssign = res.allocation
                })
            },
            getPermissionStatus() {
                this.$axios.post('/cms/stores/stores/selectRegionLeaderUser', {
                    userId: JSON.parse(sessionStorage.getItem("cmsUser")).userId
                }).then((res) => {
                    this.isAssignAble = true
                })
            }
        },
        components: {},
        computed: {}
    }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="stylus">
    .storeManageHandle {
        .mapDialog {
            display: flex;
            flex-direction: column;
            .el-dialog__body {
                flex: 1;
            }
        }
    }

    .map-Container {
        height: 100%;
        position: relative;
        .search-box {
            position: absolute;
            left: 80px;
            top: 10px;
        }
        .city-container {
            position: absolute;
            right: 30px;
            top: 10px;
            z-index: 1000;
            text-align: right;
            .city-container-current {
                display: inline-block;
                margin-bottom: 10px;
                padding: 10px 20px;
                background-color: #fff;
                border: 1px solid #EBEEF5;
                box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
            }
            .box-card {
                text-align: left;
            }
        }
    }
</style>
